#!/bin/sh

# dist-test-cases --- Generate Makefile.am and fragments of autoconf ac file for Units and Tmain dir
#
# COPYRIGHT NOTICE SHOULD BE HERE
#

#
# Originally this file generates just one file with much "EXTRA_DISTS += " lines.
# However, now we have so many test related files, EXTRA_DISTS becomes too long
# to pass it to execve.
# See http://gnu-automake.7480.n7.nabble.com/argument-list-too-long-in-project-with-many-files-td21323.html
#
# This second version generates multiple Makefile.am files to make each EXTRA_DISTS in the Makefile.am
# short.
#
print_am_header()
{
    echo "# -*- makefile -*-"
    echo "# Generated by $0"
    echo
}

print_m4_header()
{
    m4_top=$1

    echo "dnl -*- autoconf -*-"
    echo "dnl Generated by $0"
    echo
    echo 'AC_CONFIG_FILES(['"${m4_top}"/Makefile'])'
}

make_am_sub_with_git ()
{
    sub_d=$1
    sub_f=

    print_am_header
    echo "EXTRA_DIST    ="

    cd "${sub_d}"
    for sub_f in $(git ls-files .); do
	echo "EXTRA_DIST   +=" "${sub_f}"
    done
    cd ..

}

make_am_with_git ()
{
    git_top=$1
    top_d=

    print_am_header
    echo "DIST_SUBDIRS  ="
    echo "EXTRA_DIST    ="
    echo

    cd "${git_top}"
    for top_d in $(git ls-tree --name-only HEAD | sort); do
	if [ -d "${top_d}" ]; then
	    if [ "${top_d##*.}" = "r" ]; then
		echo "DIST_SUBDIRS +=" "${top_d}"
		make_am_sub_with_git ${top_d} > ${top_d}/Makefile.am
		echo "AC_CONFIG_FILES([${git_top}/${top_d}/Makefile])" >> dist.m4
	    else
		for sub_f in $(git ls-files ${top_d}); do
		    echo "EXTRA_DIST   +=" "${sub_f}"
		done
	    fi
	else
	    echo "EXTRA_DIST   +=" "${top_d}"
	fi
    done
    cd ..
}

rm -f Tmain/dist.m4
print_m4_header Tmain >> Tmain/dist.m4
make_am_with_git Tmain > Tmain/Makefile.am

rm -f Units/dist.m4
print_m4_header Units >> Units/dist.m4
make_am_with_git Units > Units/Makefile.am
